import cn from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router';
import Label from '../../../../../../components/Label';
import { CaretRightOutlined } from '@ant-design/icons';
import { Collapse } from 'antd';
import ForeignLinks from './foreignLinks';
import OtherInfo from './other';
import ShowTC from './other/ShowTC';
import s from './style.module.css';
import Icon from '../../../../../Home/icon';
import fetch from 'API/fetch';
import { WARNING_SECURITYEVENT_MAP } from '../../../../../../../common/constants';
import { datetime } from '../../../../../../../common/formatter';
import Anchor from '@knownsec/react-component/dist/Anchor';
import AddYunaqBlacklist from '../../../../../../components/AddYunaqBlacklist';
import Breadcrumb, { Item } from '../../../../../../components/Breadcrumb';
import Loading from '@knownsec/react-component/dist/Loading';

const { Panel } = Collapse;
const { Link: ALink } = Anchor;

const levelMap = {
  5: '严重',
  4: '高危',
  3: '中危',
  2: '低危',
  1: '低危',
  0: '低危'
}
const reasonMap = {
	1: '暂不关注',
	2: '误报',
	3: '其他'
}
function DetailP({
	className,
	location,
	location: { sendState },
	match: {
		params: { taskId },
	},
}) {
	sendState && sessionStorage.setItem('state', JSON.stringify(sendState));
	const state = JSON.parse(sessionStorage.state);
	const [data, setData] = React.useState();
	const [hasDetails, setHasDetails] = React.useState(null);
	const [loading, setLoading] = React.useState(false);

	const arrtype = ['违规内容'];
	const getDate = async () => {
		setLoading(true)
		const isIgnore = location.pathname.includes('/policy-manage/ignore-risk-detail')

		const res = await fetch(
			isIgnore ? `/api/v2/tasks/warning/ignore?warning_id=${state.warning_id}` : `/api/v2/tasks/securityEvent/evidence?id=${state.taskId}&warningId=${state.id}`,
			{
				method: 'GET',
			}
		);
		if (res.code === 200) {
			const data_ = JSON.parse(JSON.stringify(res?.data) || null) || {}
			delete data_.detail
			const results = isIgnore ? {...res?.data?.detail, ...data_, isIgnore} : res.results;
			setData(results);
			codeDetails(results);
		}
		setLoading(false)
	};
	const genExtra = type => {
		let isShow = false;
		const str = Object.keys(type)
			.map(e => {
				return WARNING_SECURITYEVENT_MAP[e];
			})
			.join('、');
		for (let index = 0; index < arrtype.length; index++) {
			if (str.includes(arrtype[0])) {
				isShow = true;
				break;
			}
		}
		const style = { 'margin-right': '4rem' };
		return (
			<>
				<span className={s.typeSp} style={isShow ? style : {}}>
					{str}
				</span>
			</>
		);
	};
	const ShowCodeBtn = type => {
		let isShow = false;
		const str = Object.keys(type)
			.map(e => {
				return WARNING_SECURITYEVENT_MAP[e];
			})
			.join('、');
		for (let index = 0; index < arrtype.length; index++) {
			if (str.includes(arrtype[0])) {
				isShow = true;
				break;
			}
		}
		if (isShow) {
			return (
				<div className={s.seeCode}>
					<ShowTC info={type}>查看源码</ShowTC>
				</div>
			);
		}
	};
	const sretTitle = title => {
		switch (title) {
			case '坏链':
				return <span className={s.titleSpan}>坏链接：</span>;
			case '暗链':
				return <span className={s.titleSpan}>链接：</span>;
			default:
				break;
		}
	};
	const showTable = (title, data) => {
		if (title === '风险外链') {
			return (
				<div className={s.CollapseBox}>
					{/* <span className={s.titleSpan}>风险外链：</span> */}
					<Collapse
						defaultActiveKey={['0']}
						className={s.collapse}
						expandIconPosition="left"
						// collapsible="header"
						expandIcon={({ isActive }) => (
							<CaretRightOutlined
								style={{ color: '#ccc' }}
								rotate={isActive ? 270 : 90}
							/>
						)}
					>
						{data
							? Object.keys(data?.links).map((e, i) => {
									return (
										<>
											{ShowCodeBtn(data?.links[e])}
											<Panel
												forceRender={true}
												header={e}
												key={i}
												extra={genExtra(data?.links[e])}
											>
												<ForeignLinks info={data ? data.links[e] : {}} />
											</Panel>
										</>
									);
							  })
							: null}
					</Collapse>
				</div>
			);
		} else {
			return (
				<div className={s.CollapseBox}>
					{/* {sretTitle(state.title)} */}
					<OtherInfo type={title} data={data} />
				</div>
			);
		}
	};
	const codeDetails = data => {
		// 风险外链
		const style = { color: '#fff', background: '#e70c0c' };
		let str = '';
		const dom = [];
		if (!data?.links) {
			setHasDetails(null);
		}
		if (state.title === '风险外链') {
			Object.values(data.links).forEach(links => {
				Object.values(links).forEach(val => {
					if (!Array.isArray(val)) {
						setHasDetails(null);
					}
					val.forEach(item => {
						if (!item.risk_evidences) {
							return false;
						}
						item.risk_evidences.forEach(code => {
							str = code.split(item.risk_domain);
							dom.push(
								<p className={s.codeRow}>
									{str.map((e, i) => {
										if (i < str.length - 1) {
											return (
												<>
													<span>{e}</span>
													<span style={style}>{item.risk_domain}</span>
												</>
											);
										} else {
											return (
												<>
													<span>{e}</span>
													<p>......</p>
												</>
											);
										}
									})}
								</p>
							);
						});
					});
				});
			});
		} else {
			const rs = data?.results || data?.links;
			rs.forEach(val => {
				if (!val.evidences?.length) {
					return false;
				}
				let key = val.link || val.pattern;
				key = key.toLowerCase();
				val.evidences.forEach(code => {
					str = code.split(key);
					dom.push(
						<p className={s.codeRow}>
							{str.map((e, i) => {
								if (i < str.length - 1) {
									return (
										<>
											<span>{e}</span>
											<span style={style}>{key}</span>
										</>
									);
								} else {
									return (
										<>
											<span>{e}</span>
											<p>......</p>
										</>
									);
								}
							})}
						</p>
					);
				});
			});
		}

		if (dom[0]) {
			setHasDetails(
				<div>
					{dom.map(e => {
						return e;
					})}
				</div>
			);
		} else {
			setHasDetails(null);
		}
	};
	const bread = () => {
		if (location.pathname.includes('/asset-manage/manage/web')) {
			return (
				<Breadcrumb>
					<Item disabled key="asset-manage">
						资产管理
					</Item>
					<Item key="manage/web">Web资产</Item>
					<Item key="Detail">详情</Item>
					<Item>威胁详情</Item>
				</Breadcrumb>
			);
		} else if (location.pathname.includes('/policy-manage/ignore-risk-detail')) {
			return <Breadcrumb>
				<Item disabled key="policy-manage">
					综合管理
				</Item>
				<Item key="ignore-risk-manage">已忽略威胁</Item>
				<Item>威胁详情</Item>
			</Breadcrumb>
		} else {
			return (
				<Breadcrumb>
				<Item key="job-manage" disabled>
					任务管理
				</Item>
				<Item key="web-task">Web安全监测</Item>
				<Item key={`detail?id=${state.atid}&type=${state.taskType}&tag=security_event`}>监测结果</Item>
				{state.isHistory &&
					<Item key={`history?asset_task_id=${state.atid}&task_id=${state.taskId}&task_types=security_event`}>历史任务</Item>
				}
				<Item key="">威胁详情</Item>
			</Breadcrumb>
			);
		}
	};
	React.useMemo(() => {
		getDate();
	}, []);
	return (
		<div className={cn(className, s.detail)}>
			{bread()}
			<Loading show={loading} label="" />
			<div className={cn(s.content, 'df fdc')}>
				<div>
					<div className={s.cydEnabled}>
						{state.cydEnabled && state.title !== '坏链' && (
							<AddYunaqBlacklist
								size="small"
								taskId={state.taskId}
								warningId={state.id}
							/>
						)}
					</div>
					<div className={s.content1} style={{ padding: '1.5rem 1.5rem 0 1.5rem'}}>
						<Label className={s.labelDetail}>威胁详情</Label>
						<div className={cn('df aic pl10 pr10')}>
							<span className={'flex1'}>威胁名称：{data?.title}</span>
							<span className={'flex1'}>威胁等级：{levelMap[data?.level] || '- -'}</span>
							<span className={'flex1'}>发现时间：{datetime(data?.foundAt)}</span>
						</div>
						{data?.isIgnore && <div className={cn('df aic pl10 pr10 mt10')}>
							<span className={'flex1'}>
								忽略时间：{datetime(data?.ignored_time) || '暂无'}
							</span>
							<span className={'flex2'}>忽略原因：{reasonMap[data?.reason?.type]}</span>
						</div>}
					</div>
				</div>
				<div className={cn('df aifs pr mt24 flex1', s.vdBox)}>
					<Anchor
						className={s.anchoritem}
						onClick={e => e.preventDefault()}
						getContainer={() => document.getElementById('vd')}
					>
						<ALink href="#affects" title="风险地址" />
						<ALink href="#title" title={state.title} />
						{state.title === '挂马' || state.title === '坏链' ? null : <ALink href="#detail" title="风险地址源码" />}
					</Anchor>
					<div id='vd' className={cn(s.vd, 'pl10 pr10')}>
						<div id="affects">
							<Label className={cn('mb10 mt20')}>风险地址：</Label>
							<div className={s.p0_5}>{data ? data.affects : '暂无数据'}</div>
						</div>
						<div id="title">
							<Label className={cn('mb10 mt20')}>{state.title}：</Label>
							<div className={s.p0_5}>{showTable(state.title, data)}</div>
						</div>
						{state.title === '挂马' || state.title === '坏链' ? null : (
							<div id='detail'>
								<div className={s.content1}>
									<Label className={cn('mb10 mt20')}>风险地址源码</Label>
									<div>
										<span className={s.titleSpan}>抓取时间：</span>
										<span>
											{data && hasDetails !== null
												? datetime(data.foundAt) || '- -'
												: '- -'}
										</span>
									</div>
									<div className={cn(s.showBox, 'ml10 mr10')}>
										{hasDetails || (
											<div className={cn(s.empty)}>
												<Icon active="empty"></Icon>
												<span>暂无数据</span>
											</div>
										)}
									</div>
								</div>
							</div>
						)}
					</div>
				</div>
			</div>
		</div>
	);
}

DetailP.propTypes = {
	className: PropTypes.string,
	history: PropTypes.shape({
		push: PropTypes.func.isRequired,
	}).isRequired,
	location: PropTypes.any,
	match: PropTypes.shape({
		sendState: PropTypes.any,
		params: PropTypes.shape({
			taskId: PropTypes.string.isRequired,
		}).isRequired,
	}).isRequired,
	params: PropTypes.any,
};
DetailP.defaultProps = {
	className: '',
};

export default withRouter(DetailP);
